import React, {PureComponent} from 'react';
import {connect} from 'dva';
import $ from 'jquery';
import {Icon, Card, Table, Input, message, Tag, Tooltip, Button} from 'antd';
import url from 'url';
import querystring from 'querystring';
import styles from './PutInStorage.less';
import {searchNew7, searchTaobaoShop, queryQumai, queryShopPools, searchTaobaoShopGoodsUrl} from '../../services/tool';
import KXIcons from '../NicaiPool/Columns/KXIcons';
import KXShopLevel from '../NicaiPool/Columns/KXShopLevel';


const Search = Input.Search;
@connect(state => ({
  currentUser: state.user.currentUser,
  team: state.user.team,
}))

export default class PutInStorage extends PureComponent {
  state = {
    nicaiCrx: null,
    list: [],
    auctions: [],
    shopUrls: [],
    loading: false,
    shopsLoading: false,
    searchValue: '',
    shopPool: [],
    num: 0,
    shops: [],
  }
  
  auctions = []
  shops = []
  
  componentWillMount() {
    const nicaiCrx = document.getElementById('nicaiCrx')
    nicaiCrx.addEventListener('setTaobaoAuctions', this.setTaobaoAuctions)
    if (!this.state.nicaiCrx) {
      this.setState({nicaiCrx})
    }
    queryShopPools().then(shopPool => {
      this.setState({
        shopPool: shopPool.map(p => {
          const kxuan_url = url.parse(p.kxuan_url);
          const query = querystring.parse(kxuan_url.query);
          // console.log(query);
          return {...p, id: query.id};
        }),
      });
    });
  }
  
  componentWillUnMount() {
    const nicaiCrx = document.getElementById('nicaiCrx')
    nicaiCrx.removeEventListener('setTaobaoAuctions', this.setTaobaoAuctions)
  }
  
  
  auctionByNewPool = (newPool, search_url, shopPool) => {
    // console.log('line58', search_url)
    $.ajax({
      url: search_url,
      dataType: 'jsonp',
      type: 'get',
      success: (data) => {
        const aryAuctions = (data["mods"] && data["mods"]["itemlist"]) ? data["mods"]["itemlist"]["data"]["auctions"] : []; // object
        let auctions = this.auctions
        // console.log('line66', this.auctions)
        if (aryAuctions.length >= 1) {
          aryAuctions.forEach(item => {
            const auct = auctions.find(item1 => item1.detail_url === item.detail_url);
            if (!auct) {
              auctions.push({...item, pools: [newPool]});
            } else {
              // const po = auct.pools.find(item2 => item2.kxuan_url === newPool.kxuan_url);
              // if (!po) auct.pools.push(newPool);
              auct.pools.push(newPool)
            }
            this.searchGoodGoods(item)
          })
        }
        this.setState({
          loading: false,
          num: this.state.num + 1,
        }, () => {
          if (this.state.num === shopPool.length) {
            const tempAuctions = [];
            this.auctions.forEach(item => {
              if (!tempAuctions.find(item1 => item1.shopLink === item.shopLink)) {
                tempAuctions.push(item);
              }
            });
            tempAuctions.forEach((item) => {
              this.searchTaobaoShop(item);
            });
            if (this.auctions.length === 0) {
              message.info('未找到');
            } else {
              // console.log('line 100', this.shops)
              this.setState({
                auctions: auctions,
                shops: this.shops,
              })
            }
          }
        })
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
      },
    })
  }
  
  auctionByShopPool = (valueInp) => {
    // console.log('line 107', valueInp)
    const shopPool = this.state.shopPool
    for (let i = 0; i < shopPool.length; i++) {
      let pool = shopPool[i]
      const kxuan_url = url.parse(pool.kxuan_url);
      const query = querystring.parse(kxuan_url.query);
      let search_url = `https://kxuan.taobao.com/searchSp.htm?ajax=true&callback=jsonp2711&q=${
        valueInp}&${kxuan_url.query}&nested=we&number=${Math.random()}`;
      // console.log(search_url);
      const newPool = {...pool, kxuan_url_with_q: `${pool.kxuan_url}&q=${valueInp}`};
      this.auctionByNewPool(newPool, search_url, shopPool)
    }
  }
  
  setGoodsInfo = (shopUrls) => {
    for (let s of shopUrls) {
      this.setState({
        num: 0,
        loading: true,
        auctions: [],
      })
      this.auctions = []
      this.auctionByShopPool(s)
    }
  }
  
  handleSearch = () => {
    const {searchValue} = this.state;
    let valueInp = searchValue;
    if (valueInp == null || valueInp.slice(0, 8) != 'https://') {
      message.warn('请输入要搜索店铺链接')
      return
    } else {
      let host = valueInp.split('/')[2]
      // console.log('host', host)
      let s = host.split('.')
      let s1 = s[s.length - 2]
      let notTaobo = (s1 != 'taobao' && s1 != 'tmall')
      if (notTaobo || s[0] === 'item' || s[0] === 'detail') {
        message.warn('请输入正确店铺链接')
        return
      }
    }
    valueInp = 'https://' + valueInp.split('/')[2]
    this.setState({
      loading: true,
    })
    this.state.nicaiCrx.innerText = JSON.stringify({'shopUrl': valueInp, 'sleep': 0.5})
    const customEvent = document.createEvent('Event')
    customEvent.initEvent('getTaobaoAuctions', true, true)
    this.state.nicaiCrx.dispatchEvent(customEvent)
  }
  
  setTaobaoAuctions = (e) => {
    const d = JSON.parse(e.target.innerText)
    // const d = {'auctions': ['https://item.taobao.com/item.htm?id=545118671945', 'https://item.taobao.com/item.htm?id=528368848699']}
    console.log('d.auctions', d.auctions)
    // console.log(new Set(d.auctions))
    if (d.auctions == null || d.auctions.length <= 0 || d.auctions[0].length < 7) {
      this.setState({
        loading: false,
      })
      return
    }
    this.setState({
      auctions: [],
      shops: [],
      num: 0,
      loading: true,
      shopsLoading: true,
      shopUrls: d.auctions,
    })
    let pagination = {
      current: 1,
      pageSize: 10,
    }
    this.nextPage(pagination)
  }
  
  nextPage = (pagination) => {
    // console.log('pagination', pagination)
    const {shopUrls} = this.state
    const {current, pageSize} = pagination
    const start = (current - 1) * pageSize
    const end = start + pageSize
    // console.log('start', start, 'end', end)
    // console.log('slice', shopUrls.slice(start, end))
    this.setGoodsInfo(shopUrls.slice(start, end))
  }
  
  searchTaobaoShop = (auction) => {
    // console.log(auction.shopLink);
    const urlObj = url.parse(auction.shopLink);
    const query = querystring.parse(urlObj.query);
    searchTaobaoShop(query).then(result => {
      // console.log(result);
      const shops = this.shops
      const shop = shops.find(item => item.url === result.url);
      if (!shop) {
        shops.push(result);
        // this.setState({shops});
      }
    });
  }
  
  searchGoodGoods = (auction) => {
    let auctions = this.auctions
    queryQumai({text: auction.detail_url}).then(result => {
      // console.log(result);
      let goodGoods = '';
      const innerText = result.data.htmls
      if (innerText) {
        goodGoods = innerText.split('有好货已入库')[1].split('条')[0]
      }
      // console.log(innerText, goodGoods);
      for (let i = 0; i < auctions.length; i ++) {
        if (auctions[i].detail_url === auction.detail_url) {
          auctions[i].goodGoods = goodGoods;
        }
      }
    });
  }
  
  clearInputValue = () => {
    this.setState({
      searchValue: '',
      auctions: [],
      shops: [],
      shopUrls: [],
    })
  }
  
  applyForStorage = (record, shop) => {
    this.props.dispatch({
      type: 'auction/add',
      payload: {
        category: record.category,
        collect_text: record.collect_text,
        comment_count: record.comment_count,
        comment_url: record.comment_url, // "//item.taobao.com/item.htm?id=17010160764&on_comment=1"
        detail_url: record.detail_url, // "//item.taobao.com/item.htm?id=17010160764"
        icon: record.icon, // [{icon_key: "icon-talent-yingxiao", show_type: "0", icon_category: "baobei", outer_text: "0",…}]
        item_loc: record.item_loc, // "浙江 衢州"
        kid: record.kid, // "224"
        nick: record.nick, // "高山开化龙顶"
        nid: record.nid, // "17010160764"
        p4pTags: record.p4pTags,
        pic_url: record.pic_url, // "//gw.alicdn.com/img/bao/uploaded/i4/197556695/TB2xOMajXGWBuNjy0FbXXb4sXXa_!!197556695.jpg"
        pid: record.pid,
        q_score: record.q_score, // "品质2档"
        raw_title: record.raw_title, // "龙井绿茶2018新茶上市春茶钱江源龙井明前特<span class=H>AAA</span>高山野生茶叶250g"
        shopLink: record.shopLink, // "//store.taobao.com/shop/view_shop.htm?user_number_id=197556695"
        shopcard: record.shopcard, // {delivery: [0, 1, 0], service: [0, 1, 0], description: [0, 1, 0], levelClasses: []}
        title: record.title, // "龙井绿茶2018新茶上市春茶钱江源龙井明前特<span class=H>AAA</span>高山野生茶叶250g"
        user_id: record.user_id, // "197556695"
        view_fee: record.view_fee, // "10.00"
        view_price: record.view_price, // "175.00"
        view_sales: record.view_sales, // "14人付款"
        shop: {
          userId: shop.userId, // "725677994",
          isTmall: shop.isTmall, // 1,
          title: shop.title, // "天猫超市",
          url: shop.url, // "//shop67597230.taobao.com",
          ratesum: shop.ratesum, // "20",
          encodedNick: shop.encodedNick, // "%E5%A4%A9%E7%8C%AB%E8%B6%85%E5%B8%82",
          levelClasses: shop.levelClasses, // [{"levelClass":"icon-supple-level-jinguan"},{"levelClass":"icon-supple-level-jinguan"},{"levelClass":"icon-supple-level-jinguan"},{"levelClass":"icon-supple-level-jinguan"},{"levelClass":"icon-supple-level-jinguan"}],
          favorableRate: shop.favorableRate, // "100.00%",
          encryptedUserId: shop.encryptedUserId, // "UMGIbMCcuOFk0",
          industryRate: shop.industryRate, // "100%",
          industry: shop.industry, // "家居用品",
          matchDescription: shop.matchDescription, // "4.92",
          serviceAttitude: shop.serviceAttitude, // "4.88",
          deliverySpeed: shop.deliverySpeed, // "4.89",
          descriptionCompared: shop.descriptionCompared, // {"rate":"37.35%","n":1,"class":"morethan","text":"比同行均值高","numberClass":"h"},
          attitudeCompared: shop.attitudeCompared, // {"rate":"31.92%","n":1,"class":"morethan","text":"比同行均值高","numberClass":"h"},
          deliveryCompared: shop.deliveryCompared, // {"rate":"37.54%","n":1,"class":"morethan","text":"比同行均值高","numberClass":"h"},
          openYears: shop.openYears, //  "7",
          openYearsText: shop.openYearsText, // "7年老店",
          isQiye: shop.isQiye, // 0
        },
        pools: record.pools, // 选品池
        goodGoods: Number(record.goodGoods),
        creator_id: this.props.currentUser._id,
        team_id: this.props.team._id,
      },
      callback: result => {
        if (result.error) {
          message.error(result.msg)
        } else if (result.auction) {
          message.success('入库成功')
        } else {
          message.error('未知错误\n', result)
        }
      }
    })
  }
  
  render() {
    const {auctions, shops, searchValue} = this.state;
    const columns_goods = [
      {
        title: '宝贝标题',
        dataIndex: 'raw_title',
        render: (val, record) => <a href={record.detail_url} dangerouslySetInnerHTML={{__html: val}} target="_blank"/>,
        width: '240px'
      },
      {
        title: '宝贝标签',
        dataIndex: 'icon',
        render: (val, record) => <KXIcons icon={val}/>
        
      },
      {
        title: '新七条',
        dataIndex: 'new7',
        render: (val, record) => {
          const str = record.icon && record.icon.find(item => /新7条|新七条|营销/.test(item.innerText));
          return str ? '符合' : '不符合';
        }
      },
      {
        title: '有好货入库',
        dataIndex: 'goodGoods',
      },
      {
        title: '店铺',
        dataIndex: 'shop',
        render: (val, record) => {
          const urlObj = url.parse(record.shopLink);
          const query = querystring.parse(urlObj.query);
          const shop = this.state.shops.find(item => item.userId === query.user_number_id);
          if (shop) return <a href={shop.url} target="_blank">{shop.title}</a>;
          return '';
        },
      },
      {
        title: '好评率',
        dataIndex: 'favorableRate',
        render: (val, record) => {
          const urlObj = url.parse(record.shopLink);
          const query = querystring.parse(urlObj.query);
          const shop = this.state.shops.find(item => item.userId === query.user_number_id);
          if (shop) return shop.favorableRate;
          return '';
        },
      },
      // {
      //   title: '月销',
      //   dataIndex: 'sale',
      // },
      {
        title: '售价',
        dataIndex: 'view_price',
      },
      // {
      //   title: '淘客比例',
      //   dataIndex: 'taoke',
      // },
      // {
      //   title: '淘客佣金',
      //   dataIndex: 'commission',
      // },
      {
        title: '选品池',
        dataIndex: 'pools',
        render: (val, record) => {
          if (val) {
            return val.map((item, index) =>
              <Tag closable={false} key={`pools${index}`}>
                <Tooltip placement="top" title={`${item.channel_name} / ${item.activity_name}`}>
                  <a href={item.kxuan_url_with_q} target="_blank">{item.channel_name}</a>
                </Tooltip>
              </Tag>);
          }
          return '';
        },
      },
      {
        title: '操作',
        dataIndex: 'action',
        render: (val, record) => {
          const urlObj = url.parse(record.shopLink);
          const query = querystring.parse(urlObj.query);
          const shop = this.state.shops.find(item => item.userId === query.user_number_id);
          return (
            <span>
              <div style={{color: '#1890ff', cursor: 'pointer'}} onClick={() => this.applyForStorage(record, shop)}>申请入库</div>
            </span>
          );
        },
      },
    ];
    return (
      <Card bordered={false}>
        <div className="dpcz">
          <div className={styles.searchBox} style={{position: 'relative'}}>
            <Search
              placeholder="请输入要搜索的店铺链接"
              enterButton="搜索"
              size="large"
              onSearch={this.handleSearch}
              onChange={(e) => this.setState({searchValue: e.target.value})}
              value={searchValue}
            />
            <Icon type="close-circle" className={styles.clearInpIcon} onClick={this.clearInputValue}/>
          </div>
          <div className={styles.dataList}>
            <Table
              loading={this.state.loading}
              dataSource={auctions}
              size="small"
              columns={columns_goods}
              rowKey={record => `${record.category}${record.nid}${record.kid}${Math.random()}`}
              onChange={this.nextPage}
              pagination = {{total: this.state.shopUrls.length}}
            />
            <div style={{marginTop: 20}}/>
          </div>
        </div>
      </Card>
    );
  }
}

